package xhwl.insurance.ui;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.Manifest;
import xhwl.insurance.R;
import xhwl.insurance.event.FreshForumListEvent;
import xhwl.insurance.event.PutQuestionsVoiceEvent;
import xhwl.insurance.event.PutQuestionsVoiceTextEvent;
import xhwl.insurance.http.api.SendForumApi;
import xhwl.insurance.http.api.UploadVoiceApi;
import xhwl.insurance.http.bean.RecordItem;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.ui.voicesupport.AudioButton;
import xhwl.insurance.ui.voicesupport.MediaPlay;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by Administrator on 2017/10/30.
 * 发送语音提问
 */

public class PutVoiceQuestionsActivity extends BaseActivity implements View.OnClickListener {
    private AudioButton mAudioButton;
    private RelativeLayout mDisplayVoiceLayout;
    private ImageView mDisplayVoicePlay;
    private TextView mDisplayVoiceTime;
    private RecordItem item;
    private int times;
    private View mView;
    private TextView mVoiceText;
    private TextView mWenZi;
    private TextView mDeletVoice;
    private RelativeLayout mRL;
    public List<RecordItem> mList = new ArrayList<RecordItem>();
    private EditText et_title;
    private String postTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_put_voice_question);
        //开启语音权限
        requestPermission();

    }

    @Override
    public void initViews() {
        initTitleViews();
        mAudioButton = (AudioButton) findViewById(R.id.btn);
        mDisplayVoiceLayout = (RelativeLayout) findViewById(R.id.voice_display_voice_layout);
        mDisplayVoicePlay = (ImageView) findViewById(R.id.voice_display_voice_play);
        mDisplayVoiceTime = (TextView) findViewById(R.id.voice_display_voice_time);
        mView = (View) findViewById(R.id.v_anime);
        mVoiceText = (TextView) findViewById(R.id.tv_voice_text);
        mWenZi = (TextView) findViewById(R.id.tv_wenzi);
        mDeletVoice = (TextView) findViewById(R.id.voice_delete);
        mRL = (RelativeLayout) findViewById(R.id.rl);

        //标题
        et_title = (EditText) findViewById(R.id.et_title);

        mAudioButton.setOnStartListener(new AudioButton.onStartListener() {
            @Override
            public void startRecord() {
                requestPermission();
                MediaPlay.stop();

            }
        });
        mAudioButton.setOnFinishListener(new AudioButton.onFinishListener() {

            private List<File> list;
            private File file;

            @Override
            public void finishRecord(String path, float time) {
                item = new RecordItem(path, (int) time);
                times = item.getTime();
                mDisplayVoiceTime.setText(times + "\"");
                Log.e("1123", "0000000000====" + item.getPath());
                if (item.getPath() != null) {
                    mDisplayVoiceLayout.setVisibility(View.VISIBLE);
                    mWenZi.setVisibility(View.GONE);
                    file = new File(item.getPath());
                    rightTextView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!TextUtils.isEmpty(item.getPath()) && null != item.getPath() && "" != item.getPath()) {
                                UploadVoiceApi api = new UploadVoiceApi(PutVoiceQuestionsActivity.this, new File[]{file});
                                HttpManager.getInstance().dealHttp(PutVoiceQuestionsActivity.this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {

                                    @Override
                                    public void onNext(ArrayList<ReferralPicBean> list) {
                                        String voiceUrl = list.get(0).getUrl_big();
                                        if (voiceUrl != null) {
                                            //发表接口
                                            postTitle = et_title.getText().toString().trim();
                                            if (postTitle.equals("")){
                                                Toast.makeText(PutVoiceQuestionsActivity.this, "发表标题不能为空", Toast.LENGTH_SHORT).show();
                                            }else{
                                                SendVoiceForum(voiceUrl);
                                            }
                                        }
                                    }
                                });
                            } else {
                                Toast.makeText(mContext, "发表的语音内容不能为空", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    mDisplayVoiceLayout.setVisibility(View.GONE);
                    mWenZi.setVisibility(View.VISIBLE);
                    rightTextView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(mContext, "发表的语音内容不能为空", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        });

    }

    private void requestPermission() {
        new RxPermissions(this).request(android.Manifest.permission.RECORD_AUDIO).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                        } else {
                            PermisionUtils.dialog(PutVoiceQuestionsActivity.this, "开启录音权限");
                        }
            }
        });
    }
    /**
     * 发表语音
     */
    private void SendVoiceForum(String post_urls) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String voice_long= String.valueOf(item.getTime());
        BaseApi api = new SendForumApi(member_id, postTitle, post_urls, "", "1",voice_long);
        HttpManager.getInstance().dealHttp(PutVoiceQuestionsActivity.this, api, new OnNextListener<HttpResp>() {

            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    ToastUtil.showToast(PutVoiceQuestionsActivity.this, "发表成功");
                    EventBus.getDefault().post(new FreshForumListEvent());
                    finish();
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }

        });
    }

    public void onEvent(PutQuestionsVoiceTextEvent event) {
        mVoiceText.setText("松手发送");

    }

    public void onEvent(PutQuestionsVoiceEvent event) {
        mVoiceText.setText("按住说话");

    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("提问");
        rightTextView.setVisibility(View.VISIBLE);
        rightTextView.setText("发表");
    }

    @Override
    public void initListener() {
        mDisplayVoicePlay.setOnClickListener(this);
        mDeletVoice.setOnClickListener(this);
        mRL.setOnClickListener(this);
        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "发表的语音内容不能为空", Toast.LENGTH_SHORT).show();
            }
        });

        et_title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 20) { //判断EditText中输入的字符数是不是已经大于20
                    et_title.setText(s.toString().substring(0, 20)); //设置EditText只显示前面20位字符
                    et_title.setSelection(20);//让光标移至末端
                    Toast.makeText(PutVoiceQuestionsActivity.this, "标题过长", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onPause() {
        super.onPause();
        MediaPlay.onPause();
        if (mAudioButton != null) {
            mAudioButton.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MediaPlay.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MediaPlay.onRelease();
        if (mAudioButton != null) {
            mAudioButton.onDestroy();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.voice_display_voice_play:
                mView.setBackgroundResource(R.drawable.voice_forum_animation);
                AnimationDrawable ad = (AnimationDrawable) mView.getBackground();
                ad.start();
                //播放录制的音频
                MediaPlay.playAudio(item.getPath(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //播放完成，停止动画效果
                        mView.setBackgroundResource(R.drawable.adj_voice);
                    }
                });
                break;
            case R.id.voice_delete:
                MediaPlay.stop();
                mView.setBackgroundResource(R.drawable.adj_voice);
                item.setPath(null);
                mDisplayVoiceLayout.setVisibility(View.GONE);
                mWenZi.setVisibility(View.VISIBLE);
                break;
            case R.id.rl:
                MediaPlay.stop();
                break;
            default:
                break;
        }
    }


}
